package se.webbzon.boltzmann.game.sequence.builder.dialogue;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import se.webbzon.boltzmann.game.object.dialogue.DialogueBackground;
import se.webbzon.boltzmann.game.object.dialogue.layout.DialogueLayout;
import se.webbzon.boltzmann.game.sequence.builder.SequenceBuilder;
import se.webbzon.boltzmann.game.sequence.builder.SequenceRowDeflation;
import se.webbzon.oschi01.friendly.Friendly;

public abstract class AbstractDialogueRowDeflation implements SequenceRowDeflation {
	
	private DialogueBackground background;
	
	private String text;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public AbstractDialogueRowDeflation() {};
	
	public AbstractDialogueRowDeflation(AbstractDialogueRow row) {
		this.text = row.getText();
		this.background = row.getBackground();
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Returns the background of this dialogue row deflation. **/
	public DialogueBackground getBackground() {
		return background;
	}
	
	/** Returns the text of this dialogue row deflation. **/
	public String getText() {
		return text;
	}
	
	@Override public void inflate(ByteBuffer buff) {
		background = DialogueBackground.values()[buff.getInt()];
		byte[] textData = new byte[buff.getShort()];
		buff.get(textData, 0, textData.length);
		try {
			text = new String(textData,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			text = "";
		}
	}

	@Override public ByteBuffer deflate(int allocate) {
		byte[] textData;
		try {
			textData = text.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			textData = new byte[0];
		}
		ByteBuffer buff = ByteBuffer.allocate(allocate + 6 + textData.length);
		buff.putInt(background.ordinal());
		buff.putShort((short) textData.length);
		buff.put(textData);
		return buff;
	}
	
	/*============================================================
	Friendly Methods
	============================================================*/
	
	@Friendly abstract AbstractDialogueRow makeRow(	SequenceBuilder builder,
													DialogueLayout layout);

}
